<?php


namespace App\Http\Rest\Shop\Service;

use App\Http\Entities\MemberEntity;
use App\Http\Entities\OrderBaseEntity;
use App\Http\Entities\OrderGoodEntity;
use App\Http\Entities\SecondHandEntity;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Log\Log;

class AliPayNotify implements \Payment\Contracts\IPayNotify
{
    /**
     * 处理自己的业务逻辑，如更新交易状态、保存通知数据等等
     * @param string $channel 通知的渠道，如：支付宝、微信、招商
     * @param string $notifyType 通知的类型，如：支付、退款
     * @param string $notifyWay 通知的方式，如：异步 async，同步 sync
     * @param array $notifyData 通知的数据
     * @return bool
     * @throws \Envms\FluentPDO\Exception
     */
    public function handle(
        string $channel,
        string $notifyType,
        string $notifyWay,
        array $notifyData
    ) {
        Log::info(
            "ali notify",
            ['channel' => $channel, 'notifyTYpe' => $notifyType, 'notifyWay' => $notifyWay, 'data' => $notifyData]
        );
        $orderNo = $notifyData['out_trade_no'];
        FDB::update('order_base')
            ->where('order_no', $orderNo)
            ->set(['notify_ret' => 1, 'notify_at' => date('Y-m-d H:i:s')])->execute();

        $orderInfo = OrderBaseEntity::getByAttr('order_no', $orderNo);
        switch ($orderInfo['order_type']) {
            case 1:
                break;
            case 2:
                $this->notifyRechargeSuccess($orderInfo, $notifyData);
                break;
            case 3:
                $this->notifySecondOrderSuccess($orderInfo, $notifyData);
                break;
            default:
                break;
        }


        return true;
    }

    public function notifyShopOrderSuccess($orderInfo, $notifyData)
    {
    }

    public function notifyRechargeSuccess(OrderBaseEntity $orderInfo, $notifyData)
    {
        $memberInfo = MemberEntity::getByPk($orderInfo->memberId());
        if ($orderInfo->orderType() == 2) {
            MemberEntity::updateByAttr(
                'member_id',
                $orderInfo->memberId(),
                ['account_balance' => $memberInfo->accountBalance() + $orderInfo->totalAmount()]
            );
        }
    }

    public function notifySecondOrderSuccess(OrderBaseEntity $orderInfo, $notifyData)
    {
        $orderGoodInfo = OrderGoodEntity::getByAttr('order_no', $orderInfo->orderNo());

        SecondHandEntity::updateByAttr('second_hand_id', $orderGoodInfo->productId(), ['status' => 2, 'is_deleted' => 1, 'deleted_at' => date('Y-m-d H:i:s')]);
    }
}
